package com.appspot.moviesessions.infrastructure;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;

public class DateUtil {

	private static final String DATE_FORMAT = "dd/MM/yyyy";
	private static final String TIME_FORMAT = "HH:mm";
	private static DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
	private static DateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
	private static DateFormat dateTimeFormat = new SimpleDateFormat(DATE_FORMAT
	        + " " + TIME_FORMAT);

	private DateUtil() {

	}

	public static Date today() {
		Calendar now = Calendar.getInstance();
		now = truncate(now, Calendar.DAY_OF_MONTH);
		return now.getTime();
	}

	public static Calendar truncate(Calendar calendar, int field) {
		return DateUtils.truncate(calendar, field);
	}

	public static String formatDate(Date date) {
		return dateFormat.format(date);
	}

	public static String formatToTime(Date time) {
	    return timeFormat.format(time);
    }
	
	public static Date tomorrow() {
		return new Date(today().getTime() + 1000 * 60 * 60 * 24);
	}

	public static Date parse(String text, String format) {
		return parse(text, new SimpleDateFormat(format));
	}

	public static Date parseToDateTime(String dateTime) {
		return truncate(parse(dateTime, dateTimeFormat), Calendar.SECOND);
    }
	
	public static Date parseToDate(String date) {
		return truncate(parse(date, dateFormat), Calendar.DAY_OF_MONTH);
	}

	
	private static Date parse(String date, DateFormat format) {
		try {
			return format.parse(date);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

	private static Date truncate(Date date, int field) {
		return DateUtils.truncate(date, field);
	}

	

	
}
